import encodings from './encodings.js'

function detectEncoding(samples) {
  let encoding = null
  if (looksLikeUtf8(samples)) {
    encoding = 'utf8'
  } else if (looksLikeWin1252(samples)) {
    encoding = 'win1252'
  }
  return encoding
}
function decodeSamples(enc, samples) {
  return samples.map((buf) => {
    return encodings.decodeString(buf, enc).trim()
  }).join('\n')
}
function looksLikeWin1252(samples) {
  const ascii = 'abcdefghijklmnopqrstuvwxyz0123456789.\'"?+-\n,:;/|_$% '
  const extended = 'ßàáâãäåæçèéêëìíîïðñòóôõöøùúûüýÿ°–±’‘'
  const str = decodeSamples('win1252', samples)
  const asciiScore = getCharScore(str, ascii)
  const totalScore = getCharScore(str, extended + ascii)
  return totalScore > 0.97 && asciiScore >= 0.6
}
function looksLikeUtf8(samples) {
  const str = decodeSamples('utf8', samples)
  return str.indexOf('\ufffd') === -1
}
function getCharScore(str, chars) {
  const index = {}
  let count = 0
  str = str.toLowerCase()
  for (let i = 0, n = chars.length; i < n; i += 1) {
    index[chars[i]] = 1
  }
  for (let i = 0, n = str.length; i < n; i += 1) {
    count += index[str[i]] || 0
  }
  return count / str.length
}

export default {
  detectEncoding,
}